<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="isShowDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" prop="staffPhoto" width="200">
            <template #default="{row}">
              <img
                v-fiximg="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width:180px;height:120px"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column :formatter="formstEmployee" label="聘用形式" sortable="" prop="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" />
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="obj">
              <el-switch
                v-model="obj.row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssignRole(row.id)">角色</el-button>
              <el-button
                v-if="checkPermission('delEmployee')"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageConfig.size"
            :total="total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <addEmployee :is-show-dialog="isShowDialog" />
      <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode=false">
        <el-row type="flex" justify="center">
          <canvas ref="myCode" />
        </el-row>
      </el-dialog>
      <assign-role
        ref="assignRole"
        :is-show-dialog.sync="isShowAssignRole"
      />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employee'
import EnumEmployee from '@/api/constant/employees'
import { export_json_to_excel } from '@/vender/Export2Excel'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    addEmployee,
    AssignRole
  },
  data() {
    return {
      isShowAssignRole: false,
      isShowCode: false,
      pageConfig: {
        page: 1,
        size: 5
      },
      isShowDialog: false,
      total: 0,
      employeeList: []
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 角色
    async showAssignRole(id) {
      await this.$refs.assignRole.getCheckList(id)
      this.isShowAssignRole = true
    },
    // 显示二维码
    showCode(url) {
      if (url) {
        this.isShowCode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myCode, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 删除
    async delEmployee(id) {
      await this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delEmployee(id)
      this.$message.success('删除成功')
      if (this.employeeList.length === 1 && this.pageConfig.page > 1) {
        this.pageConfig.page--
      }
      this.getEmployeeList()
    },
    // 导出
    async exportExcel() {
      // 获取员工数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      // console.log(78, rows)
      // 数据转换
      const data = rows.map(userObj => {
        return this.objToArr(userObj)
      })
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职时间']
      // 生成excel
      export_json_to_excel({
        header: header,
        data
      })
    },
    objToArr(userObj) {
      // console.log(94, userObj)
      const userArr = []
      const zidian = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      }
      for (const key in zidian) {
        const enKey = zidian[key]
        const value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(value))
          userArr.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry') {
          userArr.push(formatDate(value))
        } else {
          userArr.push(value)
        }
      }
      // console.log(108, userArr)
      return userArr
    },
    // 获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageConfig)
      this.total = total
      // console.log(59, rows)
      this.employeeList = rows.map(user => {
        const state = Math.round(Math.random())
        return {
          ...user,
          enableState: user.enableState || state
        }
      })
    },
    // 页面切换
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.getEmployeeList()
    },
    // 聘用形式
    formstEmployee(row, col, cellVal) {
      const obj = EnumEmployee.hireType.find(item => item.id === cellVal)
      return obj ? obj.value : '未知'
    }
  }
}
</script>

<style>

</style>
